<template>
  <el-form
    ref="formRef"
    style="max-width: 600px"
    :model="equitmentForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="设备名称" prop="deviceNickname">
      <el-input v-model.number="equitmentForm.deviceNickname" />
    </el-form-item>
    <el-form-item label="语音设置" prop="voice">
      <el-input v-model="equitmentForm.voice"  autocomplete="off" />
    </el-form-item>
    <el-form-item label="状态设置" prop="status">
      <el-radio-group v-model="equitmentForm.status" >
        <el-radio value='0' size="large">禁用</el-radio>
        <el-radio value='1' size="large">启用</el-radio>
        <el-radio value='2' size="large">故障</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item>
      <div style="margin-left: auto;">
       <el-button type="primary" @click="submitForm">
        确认
      </el-button>
      <el-button @click="resetForm">重置</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
defineOptions({ name: 'UpdateEquitment' })
import { watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import * as EquitmentApi from '@/api/mall/equitment/manager'
import { on } from 'events'
const formRef = ref<FormInstance>()
const message = useMessage() // 消息弹窗
const props = defineProps({
   id:{
     type:Number,
     default:0
   }
})
const emit = defineEmits(['refresh','close'])
const equitmentForm = reactive({
  id:props.id,
  voice: '',
  status: '',
  deviceNickname:"",
  autoCut:""
})
const rules = reactive<FormRules<typeof equitmentForm>>({
  status: [{  required: true,message: '不能为空',trigger: 'blur' }],
  voice: [{  required: true,message: '不能为空',trigger: 'blur' }],
  deviceNickname: [{  required: true, message: '不能为空',trigger: 'blur' }],
})

const submitForm = () => {
  if (!formRef) return
  formRef.value?.validate((valid) => {
    if (valid) {
    EquitmentApi.updateEquitment(equitmentForm).then(res=>{
      console.log(res)
      if(res){
        message.success('修改设备成功')
        emit('close')
        emit('refresh')
      }
    }).catch(err=>{
      message.error(err.message)
    })
     
    } 
  })
}
const fetchData=()=>{
  EquitmentApi.getEquitment(props.id).then(res=>{
    if(res){
      equitmentForm.id=props.id
      equitmentForm.voice=res.voice
      equitmentForm.status= res.status+''
      equitmentForm.deviceNickname=res.deviceNickname
      equitmentForm.autoCut=res.autoCut
    }
})
}
onMounted(async()=>{
   await fetchData()
})
const resetForm = () => {
  if (formRef){
     formRef?.value?.resetFields()
  }
}
watch(
  () => props.id,
  (newid) => {
    if (newid) {
      if (props.id) {
        fetchData()
      } else {
        resetForm()
      }
    }
  }
)
//暴露对外方法
defineExpose({ })
</script>